package adminorg;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.oros.db.*;

import com.vaadin.data.Container;
import com.vaadin.data.Item;
import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.DefaultFieldFactory;
import com.vaadin.ui.Form;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.MenuBar;
import com.vaadin.ui.Panel;
import com.vaadin.ui.Table;
import com.vaadin.ui.MenuBar.MenuItem;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.MenuBar.Command;
import com.vaadin.ui.Window.Notification;
import com.vaadin.ui.themes.Runo;

public class MasterGrid extends VerticalLayout{
	/**
	 * 
	 */
	private static final long serialVersionUID = -7454045680780802604L;
	
	private MenuBar MenuBar = null;
	private MenuBar.MenuItem mAdd = null;
	private MenuBar.MenuItem mEdit = null;
	private MenuBar.MenuItem mDel = null;
	private MenuBar.MenuItem mRefresh = null;
	private DatabaseHelper dbHelp = null;
	private HorizontalLayout MenuLayout = null;
	private Button bCancel = null;
	private Button bAply = null;
	private HorizontalLayout HLayout2 = null;
	private Table Grid = null;
	private Panel MPanel = null;
	private Panel GridPanel = null;
	private VerticalLayout VLayout2 = null;
	private Form MainForm = null;
	private HorizontalLayout HLayout3 = null;
	private AETableContainer MainTableContainer = null;
	private String[] Action = null; 
	private Command menuCommand = null;
	public MasterGrid(){
			
	}
	
	public MasterGrid(DatabaseHelper dbHelper, AETableContainer MainContainer, String[] Columns,  String[] Captions, 
			DefaultFieldFactory FieldFactory, String[] Actions) throws Exception{
		this();
		this.dbHelp = dbHelper;
		this.MainTableContainer = MainContainer;
		this.Action = Actions;
		InitMainCommand();
		/*VISUAL FORM CREATE*/	
		MenuBar = new MenuBar();
		MenuBar.setImmediate(false);
		mAdd = MenuBar.addItem(dbHelp.getWords("New"), menuCommand);
		mEdit = MenuBar.addItem(dbHelp.getWords("Edit"), menuCommand);
		mEdit.setEnabled(false);
		mDel = MenuBar.addItem(dbHelp.getWords("Delete"), menuCommand);
		mDel.setEnabled(false);
		mRefresh = MenuBar.addItem(dbHelp.getWords("Refresh"), menuCommand);
		MenuLayout = new HorizontalLayout();
		MenuLayout.setImmediate(true);
		MenuLayout.addComponent(MenuBar);
		
		this.addComponent(MenuLayout);
		MenuLayout.setWidth("100%");
		HLayout2 = new HorizontalLayout();
		HLayout2.setImmediate(false);

		HLayout2.setMargin(false);
		//HLayout2.setSizeFull();
		HLayout2.setSpacing(true);
		Container SubContainer = new AESubContainer(MainContainer,true, Columns);
		Grid = new Table(null,SubContainer){
			/**
			 * 
			 */
			private static final long serialVersionUID = -2717718166726554841L;

			@Override
			protected String formatPropertyValue(Object rowId,
		            Object colId, Property property) {
				if (property.getType() == Date.class) {
				    SimpleDateFormat df =
				    new SimpleDateFormat("dd.MM.yyyy");
				    return df.format((Date)property.getValue());
				}
				if (property.getType()== Boolean.class){
					if ((Boolean)property.getValue()) return dbHelp.getWords("Yes");
						else return dbHelp.getWords("No");
				}
				if (property.getType()== String.class){
					return dbHelp.getWords((String)property.getValue());
				}

				return super.formatPropertyValue(rowId, colId, property);
			};
		};
		Grid.setImmediate(true);
		Grid.setContainerDataSource(SubContainer);
		Grid.setVisibleColumns(Columns);
		Grid.setColumnHeaders(Captions);
		Grid.setColumnCollapsingAllowed(true);
		Grid.setColumnReorderingAllowed(true);
		Grid.setSelectable(true);
		Grid.setStyleName(Runo.TABLE_SMALL);
		Grid.setWidth("650px");
		HLayout2.addComponent(Grid);
		MPanel = new Panel();
		MPanel.setCaption(dbHelp.getWords(Actions[0]));
		MPanel.setVisible(false);
		MPanel.setImmediate(false);
		VLayout2 = new VerticalLayout();
		VLayout2.setImmediate(false);
		VLayout2.setMargin(true);
		MainForm = new Form();
		MainForm.setFormFieldFactory(FieldFactory);
		HLayout3 = new HorizontalLayout();
		HLayout3.setImmediate(false);
		
		// bAply
		bAply = new Button();
		bAply.setCaption(dbHelp.getWords("Apply"));
		bAply.setImmediate(true);
		bAply.setTabIndex(5);
		HLayout3.addComponent(bAply);
		
		// bCancel
		bCancel = new Button();
		bCancel.setCaption(dbHelp.getWords("Cancel"));
		bCancel.setImmediate(true);
		HLayout3.addComponent(bCancel);

		MainForm.setFooter(HLayout3);		
		VLayout2.addComponent(MainForm);		
		MPanel.setContent(VLayout2);
		HLayout2.addComponent(MPanel);
		//ChLayout2.setExpandRatio(DocGrid, 1.0f);
		HLayout2.setSizeUndefined();
		GridPanel = new Panel();
		GridPanel.setContent(HLayout2);
		GridPanel.setScrollable(true);
		this.addComponent(GridPanel);
		addGridListeners();
		addButtonListeners();
		/*END VISUAL FORM CREATE*/
	}
	
	public MasterGrid(DatabaseHelper dbHelper, AEViewContainer MainContainer, String[] Columns,  String[] Captions, 
			DefaultFieldFactory FieldFactory, String[] Actions) throws Exception{
		this();
		this.dbHelp = dbHelper;
		this.MainTableContainer = MainContainer;
		this.Action = Actions;
		InitMainCommand();
		/*VISUAL FORM CREATE*/	
		MenuBar = new MenuBar();
		MenuBar.setImmediate(false);
		mAdd = MenuBar.addItem(dbHelp.getWords("New"), menuCommand);
		mEdit = MenuBar.addItem(dbHelp.getWords("Edit"), menuCommand);
		mEdit.setEnabled(false);
		mDel = MenuBar.addItem(dbHelp.getWords("Delete"), menuCommand);
		mDel.setEnabled(false);
		mRefresh = MenuBar.addItem(dbHelp.getWords("Refresh"), menuCommand);
		MenuLayout = new HorizontalLayout();
		MenuLayout.setImmediate(true);
		MenuLayout.addComponent(MenuBar);
		
		this.addComponent(MenuLayout);
		MenuLayout.setWidth("100%");
		HLayout2 = new HorizontalLayout();
		HLayout2.setImmediate(false);

		HLayout2.setMargin(false);
		//HLayout2.setSizeFull();
		HLayout2.setSpacing(true);
		Container SubContainer = new AESubContainer(MainContainer,true, Columns);
		Grid = new Table(null,SubContainer){
			/**
			 * 
			 */
			private static final long serialVersionUID = -2717718166726554841L;

			@Override
			protected String formatPropertyValue(Object rowId,
		            Object colId, Property property) {
				if (property.getType() == Date.class) {
				    SimpleDateFormat df =
				    new SimpleDateFormat("dd.MM.yyyy");
				    return df.format((Date)property.getValue());
				}
				if (property.getType()== Boolean.class){
					if ((Boolean)property.getValue()) return dbHelp.getWords("Yes");
						else return dbHelp.getWords("No");
				}
				if (property.getType()== String.class){
					return dbHelp.getWords((String)property.getValue());
				}

				return super.formatPropertyValue(rowId, colId, property);
			};
		};
		Grid.setImmediate(true);
		Grid.setContainerDataSource(SubContainer);
		Grid.setVisibleColumns(Columns);
		Grid.setColumnHeaders(Captions);
		Grid.setColumnCollapsingAllowed(true);
		Grid.setColumnReorderingAllowed(true);
		Grid.setSelectable(true);
		Grid.setStyleName(Runo.TABLE_SMALL);
		Grid.setWidth("650px");
		HLayout2.addComponent(Grid);
		MPanel = new Panel();
		MPanel.setCaption(dbHelp.getWords(Actions[0]));
		MPanel.setVisible(false);
		MPanel.setImmediate(false);
		VLayout2 = new VerticalLayout();
		VLayout2.setImmediate(false);
		VLayout2.setMargin(true);
		MainForm = new Form();
		MainForm.setFormFieldFactory(FieldFactory);
		HLayout3 = new HorizontalLayout();
		HLayout3.setImmediate(false);
		
		// bAply
		bAply = new Button();
		bAply.setCaption(dbHelp.getWords("Apply"));
		bAply.setImmediate(true);
		bAply.setTabIndex(5);
		HLayout3.addComponent(bAply);
		
		// bCancel
		bCancel = new Button();
		bCancel.setCaption(dbHelp.getWords("Cancel"));
		bCancel.setImmediate(true);
		HLayout3.addComponent(bCancel);

		MainForm.setFooter(HLayout3);		
		VLayout2.addComponent(MainForm);		
		MPanel.setContent(VLayout2);
		HLayout2.addComponent(MPanel);
		//ChLayout2.setExpandRatio(DocGrid, 1.0f);
		HLayout2.setSizeUndefined();
		GridPanel = new Panel();
		GridPanel.setContent(HLayout2);
		GridPanel.setScrollable(true);
		this.addComponent(GridPanel);
		addGridListeners();
		addButtonListeners();
		/*END VISUAL FORM CREATE*/
	}
	
	
    private void disableMPanel(){
    	MPanel.setVisible(false);
    	if (Grid.getValue()==null){
    		mEdit.setEnabled(false);
    		mDel.setEnabled(false);
    	} else {
    		mEdit.setEnabled(true);
    		mDel.setEnabled(true);
    	}
    	mAdd.setEnabled(true);
    }
    private void enableMPanel(){
    	MPanel.setVisible(true);
    	mEdit.setEnabled(false);
    	mDel.setEnabled(false);
    	mAdd.setEnabled(false);
    }
	
	private void InitMainCommand(){
		/*ACTION COMMAND*/
		menuCommand = new Command(){
			/**
			 * 
			 */
			private static final long serialVersionUID = -6310237078935750423L;

			@Override
			public void menuSelected(MenuItem selectedItem) {
				// TODO Auto-generated method stub
				try{
					MainTableContainer.rollback();
				} catch(Exception e) {
					AEHelper.logException(e,MainTableContainer.tableName.concat(" Rollback"));
					GridPanel.getWindow().showNotification(e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
				}
				final Object ID = Grid.getValue();
				if (selectedItem.getText().equals(dbHelp.getWords("Refresh"))){
					try {
						dbHelp.getCompContainer().refresh();
						dbHelp.getCompAccContainer().refresh();
						dbHelp.getOrgschemaContainer().refresh();
						MainTableContainer.refresh();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	       	 	} else if (selectedItem.getText().equals(dbHelp.getWords("New"))){
					MPanel.setCaption(dbHelp.getWords(Action[0]));
					try{
						Object tempItemId = MainTableContainer.addItem();
						if (tempItemId==null) {
							GridPanel.getWindow().showNotification(dbHelp.getWords("ServerOverloaded"), Notification.TYPE_ERROR_MESSAGE);
							disableMPanel();
						} else {
							enableMPanel();
							MainForm.setItemDataSource(MainTableContainer.getItem(tempItemId));
						}
					} catch (Exception e){
						AEHelper.logException(e,"New ".concat(MainTableContainer.tableName));
						GridPanel.getWindow().showNotification(dbHelp.getWords("ServerError"), Notification.TYPE_ERROR_MESSAGE);
	                	disableMPanel();
					}
				} else if (selectedItem.getText().equals(dbHelp.getWords("Edit"))){
					MPanel.setCaption(dbHelp.getWords(Action[1]));
					if (ID==null){
						GridPanel.getWindow().showNotification(dbHelp.getWords("NoRecordIsChosen"), Notification.TYPE_ERROR_MESSAGE);
	                	disableMPanel();
	                	return;
	    			}
					try	{
	            		enableMPanel();
	                	MainForm.setItemDataSource(MainTableContainer.getItem(ID));
	            	}
	            	catch(Exception e)
	            	{
	            		disableMPanel();
	            		AEHelper.logException(e,MainTableContainer.tableName.concat("edit"));
	            	}
				} else if (selectedItem.getText().equals(dbHelp.getWords("Delete"))){
					if (ID==null){
						GridPanel.getWindow().showNotification(dbHelp.getWords("NoRecordIsChosen"), Notification.TYPE_ERROR_MESSAGE);
	                	disableMPanel();
	                	return;
	    			}
					GridPanel.getWindow().addWindow(new confWindow(dbHelp.getWords("RecordDeleting"),
	            			dbHelp.getWords(Action[2]),
	            			new confWindow.Callback() {
								
								private static final long serialVersionUID = 5053817083273511190L;

								@Override
								public void onDialogResult(boolean resultIsYes) {
									
									if (resultIsYes){
		
										try {
											MainTableContainer.removeItem(ID);
											MainTableContainer.commit();
						                } catch (Exception e) {
						                	AEHelper.logException(e,MainTableContainer.tableName.concat("removal"));
						                	GridPanel.getWindow().showNotification(e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
						                }
						                Grid.select(null);
									}
									
								}
							}
	            		));
				}
				
			}};
		/*END ACTION COMMAND*/
	}
	
	private void addGridListeners(){
		Grid.addListener(new Property.ValueChangeListener() {
			/**
			 * 
			 */
			private static final long serialVersionUID = -8122985276329485835L;

			@Override
			public void valueChange(ValueChangeEvent event) {
				// TODO Auto-generated method stub
				Property property = event.getProperty();
		        if (property == Grid) {
		            Item item = Grid.getItem(Grid.getValue());
		            if (item != MainForm.getItemDataSource()) {
		            	disableMPanel();	            	
		            }
		        }
			}
			
		});
	}
	private void addButtonListeners(){
		bAply.addListener(new Button.ClickListener() {
			/**
			 * 
			 */
			private static final long serialVersionUID = 7560226091431515605L;

			@Override
			public void buttonClick(ClickEvent event) {
				// TODO Auto-generated method stub
				MainForm.commit();
				if (!MainForm.isValid()) {
	                return;
	            }
				try{
					MainTableContainer.commit();
				} catch (Exception e){
					AEHelper.logException(e,"Apply button click");
					GridPanel.getWindow().showNotification(dbHelp.getWords("ServerError"), e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
				}
				disableMPanel();
			}
			
		});
		bCancel.addListener(new Button.ClickListener() {
			/**
			 * 
			 */
			private static final long serialVersionUID = -8792839358393195709L;

			@Override
			public void buttonClick(ClickEvent event) {
				// TODO Auto-generated method stub
				try {
					MainTableContainer.rollback();
		        } catch (Exception e) {
		        	AEHelper.logException(e,"Cancel button");
		        	GridPanel.getWindow().showNotification(dbHelp.getWords("ServerError"), e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
		        }
				disableMPanel();
				MainForm.setItemDataSource(null);
			}});
	}
}
